<?php
class CardManager {

    private $logger;
    private $config;

    public function __construct() {
        $date = date('YmdHis');
        $this->logger = new Logger('logs/log'.$date.'.log');
        $this->config = new Config();
    }

    public function createDeck() {
        $deck = [];
        foreach ($this->config->get('suits')  as $suit) {
            foreach ($this->config->get('ranks')  as $rank) {
                $deck[] = [
                    'suit' => $suit,
                    'rank' => $rank,
                    'value' => $this->config->get('rank_values')[$rank],
                    'id' => $suit . '_' . $rank
                ];
            }
        }
        return $deck;
    }

    public function shuffleDeck($deck) {
        shuffle($deck);
        return $deck;
    }

    public function drawCards($deck, $count) {
        return array_splice($deck, 0, $count);
    }

    public function replaceCards($hand, $cardsToReplace, $newCards) {
        foreach ($cardsToReplace as $index) {
            if (isset($hand[$index])) {
                $hand[$index] = array_shift($newCards);
            }
        }
        return $hand;
    }

    public function getRankValue($rank) {
        return $this->config->get('rank_values')[$rank] ?? 0;
    }

    // 从牌堆中移除手牌
    public function removeCards($deck, $hand)
    {
        $this->logger->info("开始从牌堆中移除手牌...");

        try {
            // 提取 $deck 中所有牌的 id 作为键，值为牌的索引
            $deckIds = array_flip(array_column($deck, 'id'));
            $this->logger->info("牌堆索引构建完成，共 " . count($deckIds) . " 张牌。");

            // 遍历手牌，从牌堆中移除对应的牌
            $removedCount = 0;
            foreach ($hand as $card) {
                if (isset($deckIds[$card['id']])) {
                    unset($deck[$deckIds[$card['id']]]);
                    $removedCount++;
                    $this->logger->info("移除手牌: " . $card['id']);
                } else {
                    $this->logger->info("手牌 " . $card['id'] . " 不在牌堆中，跳过移除。");
                }
            }

            // 重新索引数组并返回
            $deck = array_values($deck);
            $this->logger->info("移除完成，共移除 " . $removedCount . " 张牌，剩余牌堆数量: " . count($deck));

            return $deck;
        } catch (Exception $e) {
            $this->logger->writeLog("移除手牌时发生异常: " . $e->getMessage(), 'error');
            throw $e; // 重新抛出异常，由上层处理
        }
    }


}
